package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.pojos.HistorySearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async//表示异步线程
    public void insert(String keyword, Integer userId) {
        //1.根据条件查询历史记录是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(
                Criteria.where("keyword").is(keyword).and("userId").is(userId)
        ), ApUserSearch.class);
        //2.如果存在，则更新时间
        if(apUserSearch!=null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.如果不存在，则判断当前用户下历史记录条数是否大于10条

        Query query=new Query();
        query.addCriteria( Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query,ApUserSearch.class);


        //3.5 封装数据
        apUserSearch=new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        //4.如果不大于10条，则直接新增
        if(apUserSearchList.size()<10){
            mongoTemplate.insert(apUserSearch);
        }else{
            //5.如果大于10条，则替换最早的那条数据
            //获取最后一条
            ApUserSearch oldApUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            //替换
            mongoTemplate.findAndReplace(Query.query(
                    Criteria.where("id").is(oldApUserSearch.getId())
            ),apUserSearch);
        }
    }

    /**
     * 加载历史记录
     *
     * @return
     */
    @Override
    public ResponseResult load() {
        //1.先获取用户id
        ApUser apUser = AppThreadLocalUtil.getApUser();
        Query query=new Query();
        query.addCriteria(Criteria.where("userId").is(apUser.getId()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 删除历史记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult del(HistorySearchDto dto) {

        mongoTemplate.remove(Query.query(
                Criteria.where("_id").is(dto.getId())
        ),ApUserSearch.class);
        return ResponseResult.okResult("删除成功");
    }
}
